﻿/**********************************************************
* AjaxScript 
* -------------------------------------------------------
* Author:Houfeng
* Email:Houzhanfeng@gmail.com
*********************************************************/

//声明对像
var __AjaxEngine = {};

//创建XmlHttp对象
__AjaxEngine.createXmlHttp = function(){
		var xmlHttp;
		try { 
			return new ActiveXObject( "Msxml2.XMLHTTP.4.0" ); 
		} catch(ex) {}
		try { 
			return new ActiveXObject( "MSXML2.XMLHTTP" ); 
		} catch(ex){}
		try { 
			return new ActiveXObject( "Microsoft.XMLHTTP" ); 
		} catch(ex){}
	   try { 	     
			return new XMLHttpRequest(); 
		} catch(ex){}	
		return null;
}

//回调服务端
__AjaxEngine.callServer = function (funname, pars, asyn, callbackfun, att){
    var rs=null;
    try {
        if(funname)
            funname = __AjaxEngine.encode(funname);
        if(pars && pars!="")
            pars = __AjaxEngine.encode(pars);
        //alert(pars);
	    //
	    var ____url="";
	    if(theForm!=null && theForm.action!=null && theForm.action!="")
	        ____url =theForm.action;
	    else 
	        ____url=window.location.href;
	    ____url =____url.split('#')[0];//.split('?')[0];
	    //
        if(____url.indexOf('?')>-1){
            ____url=____url+"&temp="+(new Date()).getTime();
        }
        else {
             ____url=____url+"?temp="+(new Date()).getTime();
        }
	    //
        var xmlHttp = __AjaxEngine.createXmlHttp(); 
        var content= null;
        if(pars!=null){
            content = "Action=CallbackServerFunction&FunctionName=" + funname + "&Parameters=" + pars;
        }
        else{
            content = "Action=CallbackServerFunction&FunctionName="+funname;
        }
        if(att!=null && att!="")
        {   content+="&"+att ; }
        else{
            theForm.__EVENTTARGET.value = "";
            theForm.__EVENTARGUMENT.value = "";
            content += "&" + __AjaxEngine.createSerializeData();
        }
         //
         xmlHttp.onreadystatechange=function(){
             if(xmlHttp.readyState == 4 ){
                if(xmlHttp.status == 200) {
                   rs=__AjaxEngine.decode(xmlHttp.responseText);
                   if(callbackfun!=null){
                       callbackfun(__AjaxEngine.handleMessage(rs)); 
                   } 
                }
                else if(xmlHttp.status == 500){
                    rs=__AjaxEngine.decode(xmlHttp.responseText);
                    document.write(rs);
                }
             }
          }
          //
          try{
                xmlHttp.open("POST",____url, asyn);
          }
          catch(ex1){
                xmlHttp.Open("POST",____url, asyn);
          }
          xmlHttp.setRequestHeader("Content-Length",content.length);
          xmlHttp.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded"); //application/x-www-form-urlencoded multipart/form-data
          try {
                xmlHttp.send(content);
          }
          catch(ex2){
                xmlHttp.Send(content);
          }
          //
          if(callbackfun==null && rs==null){
                rs=__AjaxEngine.decode(xmlHttp.responseText);
          }
	}
	catch(ex){
	    alert("Error: "+ex +" 在回调服务端时 ");
	}
	return __AjaxEngine.handleMessage(rs);
}

//处理消息
__AjaxEngine.handleMessage = function(rs){
    if(rs==null)
        return null ;
    var rv=null;
    var renderData = __AjaxEngine.parseJson(rs.substring(rs.indexOf("--BEGIN--") + 9, rs.indexOf("--END--")));
    if(renderData==null)
        return null ;
    var count=renderData.length;
    for(i=0;i<count;i++){
        if(renderData[i]["type"]=="control"){
            var ct=document.getElementById(renderData[i]["id"]);
            if(ct!=null ){
                if(renderData[i]["context"]!="")
                    ct.outerHTML=__AjaxEngine.decode(renderData[i]["context"]);
                else
                    ct.style.display='none';
            }
        }
        else if(renderData[i]["type"]=="message"){
            alert(__AjaxEngine.decode(renderData[i]["context"]));
        }
        else if(renderData[i]["type"]=="script"){
            eval(__AjaxEngine.decode(renderData[i]["context"]));
        }
        else if(renderData[i]["type"]=="return"){
            rv=(__AjaxEngine.decode(renderData[i]["context"]));
        }
        else if(renderData[i]["type"]=="viewstate"){
            theForm.__VIEWSTATE.value=(__AjaxEngine.decode(renderData[i]["context"]));
        }
        else if(renderData[i]["type"]=="ajaxviewstate"){
            theForm.__AJAXVIEWSTATE.value=(__AjaxEngine.decode(renderData[i]["context"]));
        }
    }
    return rv;
}

//创建序列过的对象
__AjaxEngine.createSerializeData = function () {
    var eles = theForm.elements;
    var serializeData = {}
    for (var i = 0; i < eles.length; i++) {
        var tag = eles[i].tagName.toLowerCase();
        var type = eles[i].type;
        if ((tag == "input" && (type == "text" || type == "hidden" || type == "password")) || tag == "textarea" || tag == "select") {
            serializeData[eles[i].name] = eles[i].value;
        }
        else if (type == "checkbox" || type == "radio") {
            if (type == "checkbox") {
                if (!serializeData[eles[i].name] && eles[i].checked)
                    serializeData[eles[i].name] = eles[i].value;
                else if (serializeData[eles[i].name] && eles[i].checked)
                    serializeData[eles[i].name] += "-" + eles[i].value;
                else if (serializeData[eles[i].name] && serializeData[eles[i].name] != "") { }
                else {
                    // serializeData[eles[i].name] = ""; 
                }
            }
            else if (eles[i].type == "radio") {
                if (eles[i].checked)
                { serializeData[eles[i].name] = eles[i].value; }
                else {
                    if (!serializeData[eles[i].name]) {
                        // serializeData[eles[i].name] = "";
                    }
                }
            }
        }
    }
    //
    var serializeDataString = "____AjaxSubmitForm=true";
    for (p in serializeData) {
        if (p != "__VIEWSTATE")
            serializeDataString += "&" + __AjaxEngine.encode(p) + "=" + __AjaxEngine.encode(serializeData[p]);
        else {
            //serializeDataString+="&"+(p)+"="+(serializeData[p]);
            //alert(serializeData[p]);
        }
    }
    return serializeDataString;
}

//将json字串转为json对象
__AjaxEngine.parseJson = function (str) {
    //alert(str);
    try {
        return eval("(" + str + ")");
    } catch (ex) {
        alert("Error: " + ex + " 在转json数据时 " + str);
    }
}

//编码
__AjaxEngine.encode = function (str) {
    // return escape(str.replaceAll("\\+", "%2B"));
    //alet(encodeURIComponent(str));
    return encodeURIComponent(str);
}

//解码
__AjaxEngine.decode = function (str) {
    return unescape(str);
    //return decodeURIComponent(str);
}
__AjaxEngine.getTheForm = function () {
    var myform = null;
    if (!theForm) {
        myform = document.getElementsByTagName('form')[0];
    }
    else {
        myform = theForm;
    }
    return myform;
}
//----------------------------------------------------------------------------------------------
//扩展原生对象outerHTML
if(typeof(HTMLElement)!="undefined" && !window.opera){ 
    HTMLElement.prototype.__defineGetter__("outerHTML",function(){ 
        var a=this.attributes, str="<"+this.tagName, i=0;for(;i<a.length;i++) 
        if(a[i].specified) 
            str+=" "+a[i].name+'="'+a[i].value+'"'; 
        if(!this.canHaveChildren) 
            return str+" />"; 
        return str+">"+this.innerHTML+"</"+this.tagName+">"; 
    }); 
    HTMLElement.prototype.__defineSetter__("outerHTML",function(s){ 
        var r = this.ownerDocument.createRange(); 
        r.setStartBefore(this); 
        var df = r.createContextualFragment(s); 
        this.parentNode.replaceChild(df, this); 
        return s; 
    }); 
    HTMLElement.prototype.__defineGetter__("canHaveChildren",function(){ 
        return !/^(area|base|basefont|col|frame|hr|img|br|input|isindex|link|meta|param)$/.test(this.tagName.toLowerCase()); 
    });
}
//扩展原生字符串对象替换所有
String.prototype.replaceAll = function (s1, s2){
    return this.replace(new RegExp(s1, "gm"), s2);
}  

